package cn.matl.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

public class CookieDemo1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-16");
        //resp.setContentType("text/html;charset=utf-8");
        resp.setCharacterEncoding("utf-16");
        PrintWriter out = resp.getWriter();

        Cookie[] cookies = req.getCookies();
        if(cookies.length > 4){  //谷歌浏览器自带4个cookie
            out.write("你上一次访问的时间是：");
            out.print("你上一次访问的时间是：");
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                if("lastLoginTime".equals(cookie.getName())){
                    //获取cookid的值
                    long lastLoginTime = Long.parseLong(cookie.getValue());
                    Date date = new Date(lastLoginTime);
                    out.write(date.toLocaleString());
                }
            }
        }else {
            out.write("欢迎，这是您第一次访问本站。");
        }
        //服务给客户端相应一哥cookie；
        Cookie cookie = new Cookie("lastLoginTime",System.currentTimeMillis()+"");
        cookie.setMaxAge(5); //cookie有效期为5秒
        resp.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
